package RMI.client.PromoManager.GUI;

/*
 * Clientes.java
 *
 * Created on 23 de Janeiro de 2008, 23:08
 */



import RMI.server.interfaces.Comunication;

import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import sisvenda.clientes.ClienteBean;

/**
 *
 * @author  Cl�udio
 */
public class Clientes extends javax.swing.JFrame {
	private Comunication objRemoto=null;
    
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	DefaultTableModel tmClientes = new DefaultTableModel(null, new String[]{"C�digo", "Nome", "Endere�o", "Telefone"});
    ListSelectionModel lsmClientes;
    List<ClienteBean> clientes;
    String tipoCadastro;
    
    /** Creates new form Clientes */
    public Clientes() {
		super();
		initComponents();
		int port = 1099;
        try {
            Registry registry = LocateRegistry.getRegistry("localhost", port);
            objRemoto = (Comunication) registry.lookup("clienteCalculadora");
            
        } catch (NotBoundException e) {
            System.out.println("Aplica��o n�o encontrada: " + e.getMessage());
        } catch (RemoteException e) {
            System.out.println(e);
        }

	}    
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" C�digo Gerado ">                          
    protected void initComponents() {
        tfPesquisaCliente = new javax.swing.JTextField();
        btPesquisaCliente = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbClientes = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        tfNome = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        tfEndereco = new javax.swing.JTextField();
        tfBairro = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        tfCidade = new javax.swing.JTextField();
        tfUf = new javax.swing.JTextField();
        tfCep = new javax.swing.JTextField();
        tfTelefone = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        btNovo = new javax.swing.JButton();
        btAlterar = new javax.swing.JButton();
        btCancelar = new javax.swing.JButton();
        btFechar = new javax.swing.JButton();
        btSalvar = new javax.swing.JButton();

        setTitle("Clientes");

        btPesquisaCliente.setText("Pesquisar");
        btPesquisaCliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                try {
					btPesquisaClienteActionPerformed(evt);
				} catch (RemoteException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            }
        });

        tbClientes.setModel(tmClientes);
        tbClientes.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        lsmClientes = tbClientes.getSelectionModel();
        lsmClientes.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                if (! e.getValueIsAdjusting()){
                    tbFornecedoresLinhaSelecionada(tbClientes);
                }
            }
        });
        jScrollPane1.setViewportView(tbClientes);

        jLabel1.setText("Nome:");

        tfNome.setEditable(false);

        jLabel2.setText("Endere\u00e7o:");

        tfEndereco.setEditable(false);

        tfBairro.setEditable(false);

        jLabel3.setText("Bairro:");

        jLabel4.setText("Cidade:");

        jLabel5.setText("UF:");

        jLabel6.setText("CEP:");

        tfCidade.setEditable(false);

        tfUf.setEditable(false);

        tfCep.setEditable(false);

        tfTelefone.setEditable(false);

        jLabel7.setText("Telefone:");

        btNovo.setText("Novo");
        btNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btNovoActionPerformed(evt);
            }
        });

        btAlterar.setText("Alterar");
        btAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAlterarActionPerformed(evt);
            }
        });

        btCancelar.setText("Cancelar");
        btCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCancelarActionPerformed(evt);
            }
        });

        btFechar.setText("Fechar");
        btFechar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btFecharActionPerformed(evt);
            }
        });

        btSalvar.setText("Salvar");
        btSalvar.setEnabled(false);
        btSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                try {
					btSalvarActionPerformed(evt);
				} catch (RemoteException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 388, Short.MAX_VALUE)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(tfPesquisaCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 298, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE)
                                .addComponent(btPesquisaCliente))
                            .addComponent(jLabel1)
                            .addComponent(tfNome, javax.swing.GroupLayout.DEFAULT_SIZE, 388, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                            .addComponent(tfEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, 266, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addGroup(layout.createSequentialGroup()
                                                .addComponent(tfCidade, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGap(15, 15, 15)
                                                .addComponent(tfUf, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(tfCep)))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel4)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 129, Short.MAX_VALUE)
                                        .addComponent(jLabel5)
                                        .addGap(24, 24, 24)
                                        .addComponent(jLabel6)
                                        .addGap(43, 43, 43))
                                    .addComponent(jLabel2))
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel3)
                                    .addComponent(tfBairro, javax.swing.GroupLayout.DEFAULT_SIZE, 115, Short.MAX_VALUE)
                                    .addComponent(tfTelefone, javax.swing.GroupLayout.DEFAULT_SIZE, 115, Short.MAX_VALUE)
                                    .addComponent(jLabel7))))
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btNovo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btAlterar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btCancelar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btFechar)
                        .addGap(36, 36, 36))))
            .addGroup(layout.createSequentialGroup()
                .addGap(162, 162, 162)
                .addComponent(btSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(168, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btAlterar, btCancelar, btFechar, btNovo, btPesquisaCliente});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfPesquisaCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btPesquisaCliente))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tfNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfBairro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5)
                    .addComponent(jLabel6)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfCidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfUf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfCep, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btNovo)
                    .addComponent(btAlterar)
                    .addComponent(btCancelar)
                    .addComponent(btFechar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btSalvar)
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btAlterar, btCancelar, btFechar, btNovo, btPesquisaCliente});

        pack();
    }// </editor-fold>                        
    
    private void btFecharActionPerformed(java.awt.event.ActionEvent evt) {                                         
        this.dispose();
    }                                        
    
    private void btCancelarActionPerformed(java.awt.event.ActionEvent evt) {                                           
        habilitarCampos();
    }                                          
    
    private void alteraCliente(){
        if (tbClientes.getSelectedRow() != -1){
            habilitarCampos();
        } else{
            JOptionPane.showMessageDialog(this, "Selecione um cliente!");
        }
    }
    
   
    
    protected boolean verificarUF(){
        if (tfUf.getText().length() > 2)
            return false;
        return true;
    }
    
    protected void alterarFornecedor() throws RemoteException{
        if (verificarCampos() && verificarUF()){
            ClienteBean cliente = new ClienteBean();
            cliente.setCodigo(clientes.get(tbClientes.getSelectedRow()).getCodigo());
            cliente.setNome(tfNome.getText().trim());
            cliente.setEndereco(tfEndereco.getText().trim());
            cliente.setBairro(tfBairro.getText().trim());
            cliente.setCidade(tfCidade.getText().trim());
            cliente.setUf(tfUf.getText().trim());
            cliente.setCep(tfCep.getText().trim());
            cliente.setTelefone(tfTelefone.getText().trim());
            objRemoto.alterarCliente(cliente);
            desabilitarCampos();
        } else{
            JOptionPane.showMessageDialog(this, "Informe o nome do cliente!");
            tfNome.requestFocus();
        }
    }
    
    private void btAlterarActionPerformed(java.awt.event.ActionEvent evt) {                                          
        tipoCadastro = "alteracao";
        alteraCliente();
    }                                         
    
    private void btSalvarActionPerformed(java.awt.event.ActionEvent evt) throws RemoteException {                                         
        if (tipoCadastro.equals("novo")){
            cadastraFornecedor();
        } else if(tipoCadastro.equals("alteracao")){
            alterarFornecedor();
        }
    }                                        
    
    protected void tbFornecedoresLinhaSelecionada(JTable tb){
        if (tb.getSelectedRow() != -1){
            tfNome.setText(clientes.get(tb.getSelectedRow()).getNome());
            tfEndereco.setText(clientes.get(tb.getSelectedRow()).getEndereco());
            tfBairro.setText(clientes.get(tb.getSelectedRow()).getBairro());
            tfCidade.setText(clientes.get(tb.getSelectedRow()).getCidade());
            tfUf.setText(clientes.get(tb.getSelectedRow()).getUf());
            tfCep.setText(clientes.get(tb.getSelectedRow()).getCep());
            tfTelefone.setText(clientes.get(tb.getSelectedRow()).getTelefone());
        } else {
            tfNome.setText("");
            tfEndereco.setText("");
            tfCidade.setText("");
            tfBairro.setText("");
            tfUf.setText("");
            tfCep.setText("");
            tfTelefone.setText("");
        }
    }
    
    private void novoCliente(){
        habilitarCampos();
        tfNome.setText("");
        tfEndereco.setText("");
        tfCidade.setText("");
        tfBairro.setText("");
        tfUf.setText("");
        tfCep.setText("");
        tfTelefone.setText("");
    }
    
    protected void cadastraFornecedor() throws RemoteException{
        if (verificarCampos() && verificarUF()){
            ClienteBean cliente = new ClienteBean();
            cliente.setNome(tfNome.getText().trim());
            cliente.setEndereco(tfEndereco.getText().trim());
            cliente.setBairro(tfBairro.getText().trim());
            cliente.setCidade(tfCidade.getText().trim());
            cliente.setUf(tfUf.getText().trim());
            cliente.setCep(tfCep.getText().trim());
            cliente.setTelefone(tfTelefone.getText().trim());
            objRemoto.cadastrarCliente(cliente);
            desabilitarCampos();
        }
    }
    
    protected boolean verificarCampos(){
        if (!tfNome.getText().trim().equals("")){
            return true;
        }
        return false;
    }
    
    private void habilitarCampos(){
        tfNome.setEditable(true);
        tfEndereco.setEditable(true);
        tfBairro.setEditable(true);
        tfCidade.setEditable(true);
        tfCep.setEditable(true);
        tfUf.setEditable(true);
        tfTelefone.setEditable(true);
        btSalvar.setEnabled(true);
    }
    
    protected void desabilitarCampos(){
        tfNome.setEditable(false);
        tfEndereco.setEditable(false);
        tfBairro.setEditable(false);
        tfCidade.setEditable(false);
        tfCep.setEditable(false);
        tfUf.setEditable(false);
        tfTelefone.setEditable(false);
        btSalvar.setEnabled(false);
    }
    
    
    private void btNovoActionPerformed(java.awt.event.ActionEvent evt) {                                       
        tipoCadastro = "novo";
        novoCliente();
    }                                      
    
    protected void listarFornecedor() throws RemoteException{
        clientes = objRemoto.listarClientes("%" + tfPesquisaCliente.getText().trim() + "%");
        mostrarClientes(clientes);
    }
    
    protected void mostrarClientes(List<ClienteBean> clientes){
        while (tmClientes.getRowCount() > 0){
            tmClientes.removeRow(0);
        }
        
        if (clientes.size() == 0){
            JOptionPane.showMessageDialog(this, "Nenhum cliente encontrado!");
        }else{
            String [] campos = new String[] {null, null, null, null};
            for (int i = 0; i < clientes.size(); i++){
                tmClientes.addRow(campos);
                tmClientes.setValueAt(clientes.get(i).getCodigo(), i, 0);
                tmClientes.setValueAt(clientes.get(i).getNome(), i, 1);
                tmClientes.setValueAt(clientes.get(i).getEndereco(), i, 2);
                tmClientes.setValueAt(clientes.get(i).getTelefone(), i, 3);
            }
        }
    }
    
    private void btPesquisaClienteActionPerformed(java.awt.event.ActionEvent evt) throws RemoteException {                                                  
        listarFornecedor();
    }                                                 
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Clientes().setVisible(true);
            }
        });
    }
    
    // Declara��o de vari�veis - n�o modifique                     
    private javax.swing.JButton btAlterar;
    private javax.swing.JButton btCancelar;
    private javax.swing.JButton btFechar;
    private javax.swing.JButton btNovo;
    private javax.swing.JButton btPesquisaCliente;
    private javax.swing.JButton btSalvar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane1;
    protected javax.swing.JTable tbClientes;
    protected javax.swing.JTextField tfBairro;
    protected javax.swing.JTextField tfCep;
    protected javax.swing.JTextField tfCidade;
    protected javax.swing.JTextField tfEndereco;
    protected javax.swing.JTextField tfNome;
    protected javax.swing.JTextField tfPesquisaCliente;
    protected javax.swing.JTextField tfTelefone;
    protected javax.swing.JTextField tfUf;
    // Fim da declara��o de vari�veis                   
    
}
